import concurrent.futures
import random

import pymysql
import requests

import xxlSetting
from erp_fangling_cn import login_by_account, owner


def getPushStatus(house_id):
    url = f'http://erp.fangline.cn/house/get-publish-status.json?houseId={house_id}'
    response = requests.post(url, headers=login_by_account.getDefaultHeaders())
    return response.json()


def pushFollow(house_id):
    content = random.choice(xxlSetting.flowData)

    token = getPushStatus(house_id)['data']
    url = f'http://erp.fangline.cn/house/writeFollowUp?houseId={house_id}&content={content}&token={token}&imgs=&deleteTag=true'
    response = requests.post(url, headers=login_by_account.getDefaultHeaders())
    print(f'房源：{house_id} 子账号填写跟进记录:{content},{response.content}')
    


def batchInsertOwner(houseParam, houses):
    if len(houses) == 0:
        return

    # 数据库连接
    conn = pymysql.connect(
        host="43.156.247.50",  # 替换为实际的主机名
        user="root",  # 替换为实际的用户名
        password="520777",  # 替换为实际的密码
        database="house"  # 替换为实际的数据库名
    )
    cursor = conn.cursor()

    # 循环每个房产
    for house in houses:
        try:
            house_id = house[0]

            print(f'房源：{house_id} 信息:{house}')

            # 查询单个房产的 owner 信息
            owners = owner.getOwner(houseParam, house_id)
            print(f'房源：{house_id} 房主信息:{owners}')
            
            pushFollow(house_id)

            # 存在则循环，并且入库
            if len(owners) > 0:
                for o in owners:
                    sql = "INSERT INTO house_owner (owner_id, house_id, owner_name, tel, cityId) VALUES (%s, %s, %s, %s, %s)"
                    values = (
                        o['ownerId'],
                        house_id,
                        o['ownerName'],
                        o['tel'],
                        o['cityId'],
                    )

                    cursor.execute(sql, values)

                # 更新状态
                updSql = "update house set is_del = 1 where house_id = %s"
                updVal = (house_id)
                cursor.execute(updSql, updVal)
                print(f'房源：{house_id} 更新状态到数据库')

                # 每个房产提交一次
                conn.commit()
                print(f'房源：{house_id} 插入房主信息到数据库')
        except Exception as e:
            print(e)

    cursor.close()
    conn.close()
